<?php
namespace home;
use models\Basedao;
use JasonGrimes\Paginator;


class User extends Home{

// 登录
function login(){

    if(isset($_POST['do_submit'])){
        $name = $_POST['name'];

        $pw = md5(md5('ew_'.$_POST['pw']));

        $db = new BaseDao();

        $user = $db->get('user',['id','name'],['name'=>$name,'pw'=>$pw]);
        
        
        if($user){
            $db->update('user',['ltime'=>time()],['id'=>$user['id']]);

            $_SESSION = $user;
            
            $_SESSION['user_token'] = md5($user['id'].$_SERVER['HTTP_HOST']);

            // 将cookie的购物车和cart表购物车数据合并
            $cart_list = unserialize(stripcslashes($_COOKIE['cart_list']));
            if(is_array($cart_list)){
                // 把表中的购物记录取出
                $data  = $db->select('cart','*',['uid'=>$user['id']]);

                // 将表的数组格式转成cookie的cart格式
                $cart_rows = [];

                foreach($data as $v){
                    $cart_rows[$v['pid']] = $v;
                }

                // 将cookie数据cart表合并
                foreach($cart_list as $k=> $v){
                    if(array_key_exists($k,$cart_rows)){
                        $db->update('cart',['pnum'=>intval($cart_rows[$k]['pnum']+$cart_list[$k]['pnum'])],['id'=>intval($cart_rows[$k]['id'])]);
                    }else{
                        $cart_info['atime'] = time(); 
                        $cart_info['pid'] = intval($k);
                        $cart_info['pnum'] = intval($v['pnum']);
                        $cart_info['uid'] = $user['id'];
                        $db->insert('cart',$cart_info);
                    }
                }

                setcookie('cart_list','',time()-3600,'/');
            }

            $this->success('/',"用户[".$user['name']."]登录成功");
            
        }else{
            $this->error('/user/login','用户名或者密码错误');
        }
    }

    $this->assign('title','登录');
    
    $this->display("user/login");
}
// 退出登录
function logout(){
    $_SESSION = array();
    if(isset($_COOKIE[session_name()])){
        setcookie(session_name(),'',time()-3600,'/');
    }
    session_destroy();
    $this->success('/user/login','退出ok');
}
// 注册
function register(){

    $db = new Basedao();

    if(!empty($_GET['name'])){
        $finduser = $db->get('user',['id','name'],['name'=>$_GET['name']]);

        if($finduser){
            echo 'false';
        }else{
            echo "true";
        }
        die();
    }

    if(isset($_POST['do_submit'])){
        // 前端验证.....用户可以跳过表单,和前端一样,都要再验证以便
        $_POST['pw'] = md5(md5('ew_'.$_POST['pw']));
        $_POST['atime'] = $_POST['ltime'] = time();

        unset($_POST['do_submit']);
        unset($_POST['pw1']);

        if($db->insert('user',$_POST)){
            $lastinsertid = $db->id();
            // 注册ok以后直接登录
            $user = $db->get('user',['id','name'],['id'=>$lastinsertid]);
            
            $_SESSION = $user;
            
            $_SESSION['user_token'] = md5($user['id'].$_SERVER['HTTP_HOST']);
            
            $this->success('/','注册ok');


        }else{
            $this->error('/user/register','注册fail');
        }
    }

    $this->assign('title','用户注册');
    $this->display('user/register');
}

// 我的订单列表
public function order(){

    // 获取数据库操作对象
    $db = new BaseDao();

    // 分页
    $num = $_GET['num'] ?? 1;

    $prosql['ORDER'] = ['id'=>'DESC'];
    $where = ['uid'=>$_SESSION['id']];


    $this->assign('get',$_GET);


    $totalItems = $db->count('order',$where);
    
    $itemsPerPage = 3;
    $currentPage = $num;
    $urlPattern = '/user/order?num=(:num)';

    $paginator = new Paginator($totalItems, $itemsPerPage, $currentPage, $urlPattern);

    $start = ($currentPage-1) * $itemsPerPage;
    $prosql['LIMIT'] = [$start,$itemsPerPage];
    $prosql = array_merge($prosql,$where);

    // 获取全部订单,按照ord排序
    $data = $db->select('order','*',$prosql);

    foreach($data as $k=>$v){
        $data[$k]['orderdata'] = $db->select('orderdata','*',['oid'=>$v['id']]);
    }

    $this->assign('paywayarr',['1'=>'支付宝','2'=>'转账付款','3'=>'货到付款']);

    // 将数据全部分给模板
    $this->assign('data',$data);
    $this->assign('fpage',$paginator);

    

    $this->assign('title','我的订单');
    $this->assign('get','order');
    $this->display('user/order');
}

// 订单详情
public function orderview($order_id){


    $db = new BaseDao();

    $info = $db->get('order','*',['id'=>$order_id,'uid'=>$_SESSION['id']]);
    $product_list = $db->select('orderdata','*',['oid'=>$order_id]);

    $this->assign($info);
    $this->assign('product_list',$product_list);

    $this->assign('paywayarr',['1'=>'支付宝','2'=>'转账付款','3'=>'货到付款']);

    $this->assign('title','订单详情');
    $this->assign('get','order');
    $this->display('user/orderview');
}

//删除订单
public function orderdel($order_id){
    $this->assign('get','order');

    $db = new BaseDao();

    $info = $db->get('order','*',['id'=>$order_id,'uid'=>$_SESSION['id'],'state'=>1]);

    if($info){
        if($db->delete('order',['id'=>$info['id']])){

            $orderdata = $db->select('orderdata',['id','pid','pnum'],['oid'=>$info['id']]);
            // 库存加回去
            foreach($orderdata as $v){
                $db->update('product',['num[+]'=>$v['pnum']],['id'=>$v['pid']]);
            }
    
            $db->delete('orderdata',['oid'=>$order_id]);
    
            $this->success('/user/order','订单删除ok');
        }else{
            $this->error('/user/order','删除fail');
        }
    
    }else{
        $this->error('/user/order','抱歉,已付款订单不可以删除');

    }




} 

// 我的收藏
public function collect(){
    $db = new BaseDao();

    // 分页
    $num = $_GET['num'] ?? 1;

    $prosql['ORDER'] = ['collect.id'=>'DESC'];
    $where['collect.uid'] = $_SESSION['id']; 

    $totalItems = $db->count('collect',['[>]product'=>['pid'=>'id']],'*',$where);
    
    $itemsPerPage = 3;
    $currentPage = $num;
    $urlPattern = '/user/collect?num=(:num)'.$name.$content.$uname;

    $paginator = new Paginator($totalItems, $itemsPerPage, $currentPage, $urlPattern);

    $start = ($currentPage-1) * $itemsPerPage;
    $prosql['LIMIT'] = [$start,$itemsPerPage];
    $prosql = array_merge($prosql,$where);

    // 获取全部评价,按照ord排序
    $data = $db->select('collect',
    ['[>]product'=>['pid'=>'id']],
    ['collect.id','collect.pid','collect.uid','collect.atime','product.name','product.money','product.logo']
    ,$prosql);
    // 将数据全部分给模板
    $this->assign('data',$data);
    $this->assign('fpage',$paginator);

    // ----------------------------       
    $this->assign('title','我的收藏');
    $this->assign('get','collect');
    $this->display('user/collect');
} 
public function collectdel(){
    $db = new BaseDao();

    if($db->delete('collect',['pid'=>$_GET['pid'],'id'=>$_GET['id']])){

        $db->update('product',['collectnum[-]'=>1],['id'=>$_GET['pid']]);
        $this->success('/user/collect','删除ok');
    }else{
        $this->error('/user/collect','删除fail');

    }

    $this->assign('get','collect');

} 

// 我的咨询
public function ask(){
    $db = new BaseDao();

    // 分页
    $num = $_GET['num'] ?? 1;

    $prosql['ORDER'] = ['ask.atime'=>'DESC'];
    $where['ask.uid'] = $_SESSION['id']; 

    $totalItems = $db->count('ask',['[>]product'=>['pid'=>'id']],'*',$where);
    
    $itemsPerPage = 3;
    $currentPage = $num;
    $urlPattern = '/user/ask?num=(:num)'.$name.$content.$uname;

    $paginator = new Paginator($totalItems, $itemsPerPage, $currentPage, $urlPattern);

    $start = ($currentPage-1) * $itemsPerPage;
    $prosql['LIMIT'] = [$start,$itemsPerPage];
    $prosql = array_merge($prosql,$where);

    // 获取全部评价,按照ord排序
    $data = $db->select('ask',
    ['[>]product'=>['pid'=>'id']],
    ['ask.id','ask.pid','ask.uid','ask.uip',
    'ask.atime','ask.uname','ask.replytext','ask.replytime','ask.state','ask.asktext',
'product.name','product.logo']
    ,$prosql);
    // 将数据全部分给模板
    $this->assign('data',$data);
    $this->assign('fpage',$paginator);

    // ----------------------------    
    $this->assign('title','我的咨询');
    $this->assign('get','ask');
    $this->display('user/ask');
} 

// 我的评价
public function comment(){
    $db = new BaseDao();

    // 分页
    $num = $_GET['num'] ?? 1;

    $prosql['ORDER'] = ['comment.atime'=>'DESC'];
    $where['comment.uid'] = $_SESSION['id']; 

    $totalItems = $db->count('comment',['[>]product'=>['pid'=>'id']],'*',$where);
    
    $itemsPerPage = 3;
    $currentPage = $num;
    $urlPattern = '/user/comment?num=(:num)'.$name.$content.$uname;

    $paginator = new Paginator($totalItems, $itemsPerPage, $currentPage, $urlPattern);

    $start = ($currentPage-1) * $itemsPerPage;
    $prosql['LIMIT'] = [$start,$itemsPerPage];
    $prosql = array_merge($prosql,$where);

    // 获取全部评价,按照ord排序
    $data = $db->select('comment',
    ['[>]product'=>['pid'=>'id']],
    ['comment.id','comment.pid','comment.uid','comment.uip',
    'comment.atime','comment.uname','comment.content',
'product.name','product.logo']
    ,$prosql);
    // 将数据全部分给模板
    $this->assign('data',$data);
    $this->assign('fpage',$paginator);

    // ----------------------------
    $this->assign('title','我的评价');
    $this->assign('get','comment');
    $this->display('user/comment');
} 

// 个人信息设置
public function base(){
    $db = new Basedao();
    if(isset($_POST['do_submit'])){
        unset($_POST['do_submit']);
        if($db->update('user',$_POST,['id'=>$_SESSION['id']])){
            $this->success('/user/base','基本信息修改ok');
        }else{
            $this->error('/user/base','基本信息修改fail');

        }
    }
    $this->assign($db->get('user','*',['id'=>$_SESSION['id']]));
    $this->assign('title','基本资料');
    $this->assign('get','base');
    $this->display('user/base');
} 

// 个人密码修改
public function pw(){

    $db = new Basedao();

    if(isset($_POST['do_submit'])){
        if($_POST['pw'] != $_POST['pw1']){
            $this->error('/user/pw','两次输入的密码不一致');
            
        }
        if($db->update('user',['pw'=>md5(md5('ew_'.$_POST['pw']))],['id'=>$_SESSION['id']])){
            $this->success('/user/pw','新密码设置ok');
        }else{
            $this->error('/user/pw','新密码设置fail');

        }
    }



    $this->assign('title','密码修改');
    $this->assign('get','pw');
    $this->display('user/pw');
} 
}